"""
copyright (c) 2009 Claudio Canepa
this code licensed under the new BSD license, see file license_simpledocu.txt
"""
class OutMockup(object):
    def __init__(self):
        self.text = ''

    def write(self, s):
        self.text += s

class InMockup(object):
                
    def __init__(self,text):
        self.text = text
        self.max_EOF = -1
        # self.cursor = 0 # 
        self.past_EOF = False

    def reset(self):
        if hasattr(self,'cursor'):
            delattr(self.cursor)
            
    def get_line_iterator(self,max_EOF=-1):
        if hasattr(self,'cursor'):
            # at any time only one iterator can be in use
            raise Exception
        self.max_EOF = max_EOF
        self.cursor = 0
        self.past_EOF = False
        return self
            
    def _readline(self):
        exausted = self.past_EOF
        if exausted:
            line = ''
        else:
            n = self.text.find('\n',self.cursor)
            if n<0:
                if self.cursor<len(self.text):
                    # the input ends without \n
                    n = len(self.text)
                    line = self.text[self.cursor:n]
                    self.cursor = n
                else:
                    # reading past EOF
                    line = ''
                    self.past_EOF = True # for the next call
                    exausted = True
            else:
                n = n+1
                line = self.text[self.cursor:n]
                self.cursor = n
        return line, exausted

    def next(self):
        try:
            line, past_EOF = self._readline()
        except IndexError:
            # need to call get_line_iterator before calling next
            raise Exception
        if past_EOF:
            raise StopIteration
        return line


    def readline(self):
        #(N.B.: the file.read() and file.readline() methods return an
        #empty string when they hit EOF.)
        #for testing purposes (break infinite loops) we may want to raise
        #when too much reading past EOF
        if not hasattr(self,'cursor'):
            self.get_line_iterator()
        line, past_EOF = self._readline()
        if past_EOF and self.maxEOF>-1:
            if self.maxEOF:
                self.maxEOF -= 1
            else:
                raise EOFError
        return line        
